package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.pojo.User;
import com.jt.util.ObjectMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;

import com.jt.mapper.UserMapper;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.JedisCluster;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private JedisCluster jedisCluster;

	private static Map<Integer,String> paramMap=new ConcurrentHashMap<>();
	static {
		paramMap.put(1,"username");
		paramMap.put(2,"phone");
		paramMap.put(3,"email");
	}

	@Override
	public List<User> findUserAll() {
		return userMapper.selectList(null);
	}

	@Override
	public boolean checkuser(String param, Integer type) {
		String column=paramMap.get(type);
		QueryWrapper<User> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq(column, param);
		int count=userMapper.selectCount(queryWrapper);
		return count>0;
	}

	@Override
	public String doLogin(User user) {
		String md5Pass =
				DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
		user.setPassword(md5Pass);
		QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
		//根据对象中不为null的属性当做where条件.
		User userDB = userMapper.selectOne(queryWrapper);
		if(userDB == null){
			//用户名或密码错误
			return null;
		}else{ //用户名和密码正确  实现单点登录操作
			String ticket = UUID.randomUUID().toString();
			//如果将数据保存到第三方 一般需要脱敏处理
			userDB.setPassword("123456你信不??");
			String userJSON = ObjectMapperUtil.toJSON(userDB);
			jedisCluster.setex(ticket, 7*24*60*60, userJSON);
			return ticket;
		}
	}
}
